import 'dart:developer' as developer;

import 'package:get/get.dart';

/// 训练状态枚举
enum TrainingState {
  idle,      // 空闲
  preparing, // 准备中
  running,   // 运行中
  paused,    // 暂停
  completed, // 完成
  stopped    // 停止
}

/// 训练类型信息
class TrainingType {
  final int id;
  final String name;
  final String description;
  final bool isSupported;

  TrainingType({
    required this.id,
    required this.name,
    required this.description,
    required this.isSupported,
  });
}

/// 动作详情信息
class ActionDetails {
  final String actionName;
  final DateTime timestamp;
  final int duration;
  final int calories;
  final double? distance;
  final int? heartRate;
  final Map<String, dynamic> additionalData;

  ActionDetails({
    required this.actionName,
    required this.timestamp,
    required this.duration,
    required this.calories,
    this.distance,
    this.heartRate,
    this.additionalData = const {},
  });
}

/// 历史训练记录
class HistoryTrainingRecord {
  final int trainingId;
  final DateTime startTime;
  final DateTime endTime;
  final int trainingType;
  final String trainingName;
  final int duration; // 秒
  final int calories;
  final double? distance;
  final int? averageHeartRate;
  final int? maxHeartRate;
  final TrainingState state;
  final List<ActionDetails> actionDetails;
  final int rawTime; // 原始时间戳

  HistoryTrainingRecord({
    required this.trainingId,
    required this.startTime,
    required this.endTime,
    required this.trainingType,
    required this.trainingName,
    required this.duration,
    required this.calories,
    this.distance,
    this.averageHeartRate,
    this.maxHeartRate,
    required this.state,
    this.actionDetails = const [],
    this.rawTime = 0,
  });

  /// 从 CRPHistoryTrainingInfo 创建 HistoryTrainingRecord
  factory HistoryTrainingRecord.fromCRPHistoryTrainingInfo(Map<String, dynamic> info) {
    final startTime = DateTime.fromMillisecondsSinceEpoch(info['startTime'] ?? 0);
    final rawTime = info['rawTime'] ?? 0;
    final type = info['type'] ?? 0;
    
    // 根据训练类型获取名称
    String trainingName = _getTrainingTypeName(type);
    
    return HistoryTrainingRecord(
      trainingId: info['id'] ?? 0,
      startTime: startTime,
      endTime: startTime, // 暂时使用开始时间，实际应该从设备获取结束时间
      trainingType: type,
      trainingName: trainingName,
      duration: 0, // 需要从设备获取实际时长
      calories: 0, // 需要从设备获取实际卡路里
      state: TrainingState.completed, // 历史记录通常是已完成的
      rawTime: rawTime,
    );
  }

  /// 获取训练类型名称
  static String _getTrainingTypeName(int type) {
    switch (type) {
      case 0:
        return '自由训练';
      case 1:
        return '跑步';
      case 2:
        return '散步';
      case 3:
        return '骑行';
      case 4:
        return '游泳';
      case 5:
        return '健身';
      case 6:
        return '瑜伽';
      case 7:
        return '力量训练';
      case 8:
        return '有氧运动';
      default:
        return '未知训练';
    }
  }
}

/// 运动记录数据模型
class ExerciseRecord {
  final DateTime date;
  final DateTime startTime;
  final String exerciseName;
  final String exerciseIcon;
  final int duration; // 分钟
  final int calories;
  final int? heartRate; // 心率，可选
  final bool isAutoDetected; // 是否自动检测

  ExerciseRecord({
    required this.date,
    required this.startTime,
    required this.exerciseName,
    required this.exerciseIcon,
    required this.duration,
    required this.calories,
    this.heartRate,
    this.isAutoDetected = false,
  });
}

/// 运动记录状态
class ExerciseRecordState {
  /// 是否正在加载
  RxBool isLoading = false.obs;
  
  /// 运动记录列表
  RxList<ExerciseRecord> exerciseRecords = <ExerciseRecord>[].obs;
  
  /// 当前训练状态
  Rx<TrainingState> currentTrainingState = TrainingState.idle.obs;
  
  /// 支持的训练类型列表
  RxList<TrainingType> supportedTrainingTypes = <TrainingType>[].obs;
  
  /// 历史训练记录列表
  RxList<HistoryTrainingRecord> historyTrainingRecords = <HistoryTrainingRecord>[].obs;
  
  /// 当前训练的动作详情
  RxList<ActionDetails> currentActionDetails = <ActionDetails>[].obs;
  
  /// 是否正在查询历史记录
  RxBool isQueryingHistory = false.obs;
  
  /// 是否正在查询支持的类型
  RxBool isQueryingSupportedTypes = false.obs;
  
  /// 是否正在查询动作详情
  RxBool isQueryingActionDetails = false.obs;
  
  /// 刷新运动记录
  void refreshRecords() {
    isLoading.value = true;
    
    // 清空现有数据，等待真实数据
    exerciseRecords.value = [];
    isLoading.value = false;
    
    // TODO: 从设备获取真实的运动记录数据
    print('🔍 需要从设备获取真实的运动记录数据');
  }
  
  /// 更新训练状态
  void updateTrainingState(TrainingState newState) {
    currentTrainingState.value = newState;
    print('🏃‍♀️ 训练状态更新: $newState');
  }
  
  /// 查询支持的训练类型
  void querySupportedTrainingTypes() {
    isQueryingSupportedTypes.value = true;
    
    // TODO: 从设备获取真实的支持训练类型
    print('🔍 需要从设备获取真实的支持训练类型');
    
    // 清空现有数据
    supportedTrainingTypes.value = [];
    isQueryingSupportedTypes.value = false;
  }
  
  /// 查询历史训练记录
  void queryHistoryTrainingRecords() {
    isQueryingHistory.value = true;
    
    // TODO: 从设备获取真实的历史训练记录
    print('🔍 需要从设备获取真实的历史训练记录');
    
    // 清空现有数据
    historyTrainingRecords.value = [];
    isQueryingHistory.value = false;
  }
  
  /// 更新真实的历史训练记录（从设备回调）
  void updateRealHistoryTrainingRecords(List<Map<String, dynamic>> historyData) {
    isQueryingHistory.value = true;
    
    print('🔍 开始处理真实历史训练记录数据...');
    print('📥 原始数据: $historyData');
    
    final records = <HistoryTrainingRecord>[];
    
    for (int i = 0; i < historyData.length; i++) {
      final data = historyData[i];
      try {
        print('📋 处理第 ${i + 1} 条记录: $data');
        
        final record = HistoryTrainingRecord.fromCRPHistoryTrainingInfo(data);
        
        if (record.startTime.millisecondsSinceEpoch > 0) {
          records.add(record);
          print('✅ 成功解析记录 ${i + 1}:');
          print('   - 训练ID: ${record.trainingId}');
          print('   - 训练名称: ${record.trainingName}');
          print('   - 开始时间: ${record.startTime}');
          print('   - 训练类型: ${record.trainingType}');
          print('   - 原始时间戳: ${record.rawTime}');
        } else {
          print('⚠️ 跳过无效时间戳的记录 ${i + 1}: ${data['startTime']}');
        }
      } catch (e) {
        print('❌ 解析历史训练记录 ${i + 1} 失败: $e');
        print('   原始数据: $data');
      }
    }
    
    // 按开始时间排序（最新的在前面）
    records.sort((a, b) => b.startTime.compareTo(a.startTime));
    
    historyTrainingRecords.value = records;
    isQueryingHistory.value = false;
    
    print('📊 真实历史训练记录处理完成:');
    print('   - 总记录数: ${records.length} 条');
    print('   - 有效记录: ${records.where((r) => r.startTime.millisecondsSinceEpoch > 0).length} 条');
    
    for (int i = 0; i < records.length; i++) {
      final record = records[i];
      print('   ${i + 1}. ${record.trainingName} - ${record.startTime.toString().substring(0, 19)}');
    }
    
    developer.log("真实历史训练记录: $records");
  }
  
  /// 查询动作详情
  void queryActionDetails(int trainingId) {
    isQueryingActionDetails.value = true;
    
    // TODO: 从设备获取真实的动作详情数据
    print('🔍 需要从设备获取训练ID $trainingId 的真实动作详情数据');
    
    // 清空现有数据
    currentActionDetails.value = [];
    isQueryingActionDetails.value = false;
  }
  
  /// 开始训练状态监控
  void startTrainingStateMonitoring() {
    print('🔍 开始训练状态监控');
    // TODO: 监听设备的训练状态变化
  }
  
  /// 停止训练状态监控
  void stopTrainingStateMonitoring() {
    print('⏹️ 停止训练状态监控');
    // TODO: 停止监听设备状态
  }
}
